package byx.container.annotation.extension.impl;

import byx.container.annotation.exception.UnsupportedCollectionTypeException;

import java.lang.reflect.Constructor;
import java.util.*;
import java.util.function.Function;

public class CollectionConverter {
    public static Collection<?> convert(Collection<?> collection, Class<?> collectionType) {
        if (collectionType == Collection.class) {
            return new ArrayList<>(collection);
        } else if (collectionType == List.class) {
            return new ArrayList<>(collection);
        } else if (collectionType == Set.class) {
            return new HashSet<>(collection);
        } else if (collectionType == Queue.class) {
            return new LinkedList<>(collection);
        }

        try {
            Constructor<?> constructor = collectionType.getConstructor(Collection.class);
            return (Collection<?>) constructor.newInstance(collection);
        } catch (Exception e) {
            throw new UnsupportedCollectionTypeException(collectionType, e);
        }
    }

    public static Function<Collection<?>, Collection<?>> converter(Class<?> collectionType) {
        return new Function<>() {
            @Override
            public Collection<?> apply(Collection<?> c) {
                return convert(c, collectionType);
            }

            @Override
            public String toString() {
                return String.format("convertTo(%s)", collectionType);
            }
        };
    }
}
